class Admin::CirculationListsController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def show_list
    @circulation_list_pages, @circulation_lists = paginate :circulation_lists, :per_page => 10
    @circulation_lists = CirculationList.find(:all, :conditions => 
        ["magazine_id = ?", params[:id] ])
    @magazine_id = params[:id]
  end

  def show
    @circulation_list = CirculationList.find(params[:id])
    @magazine_id = params[:magazine_id]
  end

  def new
    @circulation_list = CirculationList.new
    @magazines = Magazine.find(:all, :order => :name).map {|c| [c.name, c.id]}
    @users = User.find(:all, :order => :name).map {|c| [c.name, c.id]}
    @magazine_id = params[:magazine_id]
  end

  def create
    @circulation_list = CirculationList.new(params[:circulation_list])
    @circulation_list.magazine_id = params[:magazine_id]
    user_id = params[:circulation_list][:user_id]
    user_priority = User.find(user_id).position.hierarchy
    @circulation_list.priority = user_priority
    if @circulation_list.save
      flash[:notice] = 'Usu&aacute;rio cadastrado com sucesso na lista!<br/><br/>'
      redirect_to :action => 'show_list', :id => params[:magazine_id]
    else
      render :action => 'new'
    end
  end

  def edit
    @circulation_list = CirculationList.find(params[:id])
    @magazines = Magazine.find(:all, :order => :name).map {|c| [c.name, c.id]}
    @users = User.find(:all, :order => :name).map {|c| [c.name, c.id]}
    @magazine_id = params[:magazine_id]
  end

  def update
    @circulation_list = CirculationList.find(params[:id])
    if @circulation_list.update_attributes(params[:circulation_list])
      flash[:notice] = 'Lista atualizada com sucesso!<br/><br/>'
      redirect_to :action => 'show', :id => @circulation_list, :magazine_id => params[:magazine_id]
    else
      render :action => 'edit'
    end
  end

  def destroy
    CirculationList.find(params[:id]).destroy
    redirect_to :action => 'show_list', :id => params[:magazine_id]
  end
  
  def list
    @magazines = Magazine.find(:all)
  end
end
